#include"XmlParser.h"

XmlParser::XmlParser(char* path) {
    logd("path=%s",path);
    startParse(path);
    logd("inited!");
}

XmlParser::~XmlParser() {
    logd("deinited!");

}

XmlParser* XmlParser::getXmlParser(void) {
    return this;
}

void XmlParser::startParse(char* path) {

    xmlDocPtr pdoc = NULL;
    xmlNodePtr proot = NULL, pListParams = NULL;

    xmlKeepBlanksDefault(0);//必须加上，防止程序把元素前后的空白文本符号当作一个node
    pdoc = xmlReadFile (path, "UTF-8", XML_PARSE_RECOVER);//libxml只能解析UTF-8格式数据

    if (pdoc == NULL)
    {
        cout<<"error:can't open file!"<<endl;
        exit (1);
    }

    logd("parsing start....");
    proot = xmlDocGetRootElement (pdoc); //TypeColor
    logd("%s",proot->name);

    if (proot == NULL)
    {
        cout<<"error: file is empty!"<<endl;
        exit (1);
    }

    pListParams = proot->xmlChildrenNode;   //ListParams
    xmlChar *nodecontent;
    nodecontent=xmlNodeGetContent(pListParams);
    logd("%s,%s",pListParams->name,nodecontent);

    xmlNodePtr pnext=pListParams->next;
    while(NULL!=pnext) {
        // nodecontent=xmlNodeGetContent(pnext);
        // logd("%s,%s",pnext->name,nodecontent);
        logd("%s",pnext->name);
        xmlNodePtr pnext_child;
        pnext_child=pnext->xmlChildrenNode;
        while(NULL!=pnext_child) {
            nodecontent=xmlNodeGetContent(pnext_child);
            logd("%s,%s",pnext_child->name,nodecontent);
            tcp t;
            t.key=(const char*)pnext_child->name;
            t.value=(const char*)nodecontent;
            paramVector.push_back(t);
            pnext_child=pnext_child->next;
        }
        pnext=pnext->next;
    }

    // dumpparamVector();

/*****************释放资源********************/
    xmlFreeDoc (pdoc);
    xmlCleanupParser ();
    xmlMemoryDump ();

    logd("parsing done!");
}

std::string XmlParser::getValueFromKey(std::string key) {
    std::string result("null");
    for(tcp t:paramVector) {
        logd("%s--%s",t.key.c_str(),t.value.c_str());
        if(t.key == key) {
            logd("%s--%s",t.key.c_str(),t.value.c_str());
            result = t.value;
            break;
        }
    }
    if(result=="null") {
        loge("key:%s not found!",key.c_str());
    }
    return result;
}

void XmlParser::dumpparamVector(void) {
    logd("dump paramVector start....");
    for(tcp t : paramVector) {
        logd("%s--%s",t.key.c_str(),t.value.c_str());
    }
    logd("dump paramVector end!");
}








